package code.whmmm.util.servlet;


import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * <p><b>
 * 依赖 fastJson !
 * </b></p>
 * <br/>
 * 创建时间: 9/3/2019 11:48 AM
 *
 * @author Zero
 */
public class ServletUtil {

    private static final Logger log = LoggerFactory.getLogger(ServletUtil.class);

    /**
     * 写出 json 并且 关闭 response 流
     *
     * @param response 响应
     * @param data     响应信息
     */
    public static void writeJson(HttpServletResponse response, Object data, boolean closeResponse) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");


        PrintWriter writer = null;
        try {
            writer = response.getWriter();

            writer.write(JSONObject.toJSON(data).toString());
            writer.flush();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } finally {
            if (closeResponse && writer != null) {
                writer.close();
            }
        }

    }


    public static void writeJson(HttpServletResponse response, Object data) {
        writeJson(response, data, true);
    }

    /**
     * 判断是否是 ajax 请求
     *
     * @param request
     * @return
     */
    public static boolean determineAjax(HttpServletRequest request) {

        String requestedWith = (request).getHeader("X-Requested-With");

        return request.getHeader("x-requested-with") != null
                && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest");
    }


    public static void writeText(HttpServletResponse response, String text, boolean closeResponse) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");

        PrintWriter writer = null;
        try {
            writer = response.getWriter();
            writer.write(text);
            writer.flush();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } finally {

            if (closeResponse && writer != null) {
                writer.close();
            }
        }
    }

    public static void writeText(HttpServletResponse response, String text) {
        writeText(response, text, true);
    }

}
